<!-- 会员管理 -->
<template>
  <div>
    <!-- 查找 -->
    <div>
      <el-space wrap>
        <el-select v-model="Userbinding.status" class="m-2" placeholder="请选择用户状态">
          <el-option v-for="item in UserStatus" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-select v-model="Userbinding.level" class="m-2" placeholder="请选择用户会员等级">
          <el-option v-for="item in UserMember" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-select v-model="Userbinding.gender" class="m-2" placeholder="请选择用户性别">
          <el-option v-for="item in Usergender" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-input v-model="Userbinding.id" placeholder="请输入用户ID" />
        <el-input v-model="Userbinding.nickname" placeholder="请输入昵称" />
        <el-button type="primary" :icon="Search" @click="userlookup" >查找</el-button>
      </el-space>
    </div>

    <!-- 会员管理表格 -->
    <div style="margin-top: 20px;">
      <el-table :data="tableData.list" style="width:100%" border>
        <el-table-column prop="id" label="用户ID" align="center" sortable  />
        <el-table-column prop="nickname" label="昵称" align="center" />
        <el-table-column prop="phone" label="手机号码" align="center" />
        <el-table-column prop="gender" label="性别" align="center">
          <template #default="scope">
            <el-tag>{{scope.row.gender==2?'男':'女'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="会员等级" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.level==0?'info':'warning'">{{scope.row.level==0?'普通会员':'VIP会员'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" align="center">
          <template #default="scope">
            {{scope.row.birthday ? new Date(scope.row.birthday).birthdayTime() : "-"}}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status==0?'':'danger'">{{scope.row.status==0?'激活':'冻结'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gmtLastLogin" label="上次登录时间" align="center">
          <template #default="scope">
            {{ new Date(scope.row.gmtLastLogin).normalTime()}}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginIp" label="上次登录IP" align="center" />
        <el-table-column prop="address" label="Address" align="center" width="200%">
          <template #default="scope">
            <el-button :type="scope.row.status?'primary':'danger'" @click="ActivateUser(scope.row)" plain>
              {{scope.row.status?'激活':'冻结'}}</el-button>
            <el-button type="primary" @click="Useredit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑弹出框 -->
      <el-dialog v-model="centerDialogVisible" title="编辑" width="35%" align-center>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
          status-icon>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="ruleForm.nickname" />
          </el-form-item>
          <el-form-item label="用户手机号" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </el-form-item>
          <el-form-item label="用户性别" prop="gender">
            <el-select v-model="ruleForm.gender" placeholder="Activity zone">
              <el-option v-for="item in Usergender.slice(0,2)" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户等级" prop="level">
            <el-select v-model="ruleForm.level" placeholder="Activity count">
              <el-option v-for="item in UserMember.slice(0,2)" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="Activity count">
              <el-option v-for="item in UserStatus.slice(0,2)" :key="item.value" :label="item.name" :value="item.value"  />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" v-permission='"user:user:edit"' >修改</el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <!-- 分页 -->
    <PagingList :listdata="listdata" @Change="giterList"></PagingList>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { post } from "@/utils/request";
import { Pagination } from "#/index";
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'

let listdata = reactive(new Pagination()) //分页数据
// 分页
const giterList = (e: { page: number; limit: number; total: number; flog: { valueOf: () => boolean; }; targetAdminId?: undefined; }) => { //获取下一页的数据并赋值
  listdata = e
  getdata()
}
// 表格数据
const tableData = reactive({ list: [] as string[] })
// 选择框数据
const UserStatus = ref([{ name: '冻结', value: 1 }, { name: '激活', value: 0 }, { name: '全部', value: '' }])//用户状态
const UserMember = ref([{ name: '普通会员', value: 0 }, { name: 'VIP会员', value: 1 }, { name: '全部', value: '' }])//用户会员
const Usergender = ref([{ name: '女', value: 1 }, { name: '男', value: 2 }, { name: '全部', value: '' }]) //用户性别
const Userbinding = reactive({ status: '', level: '', gender: '', id: '', nickname: '' })
const centerDialogVisible = ref(false) //控制弹出框的显示隐藏
const ruleFormRef = ref<FormInstance>()// 表单绑定的数据
const ruleForm = reactive({ nickname: 'Hello', phone: '', gender: '', level: '', status: '' })//表单验证绑定的数据
/**
 * 手机号校验
 * @param rule 源描述符中与要验证的字段名称对应的验证规则
 * @param val 正在验证的源对象属性的值
 * @param cb 验证完成后要调用的回调函数
 */
const validatePhone = (rule: object, val: string, cb: (arg0: Error | undefined) => void) => { //手机验证
  const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|16[6]|19[89]]|17[01345678]|18[0-9]|14[579])[0-9]{8}$/
  if (regPhone.test(val)) {
    //合法手机号
    return cb(undefined)
  }
  cb(new Error('请输入合法手机号'))
}
const rules = reactive<FormRules>({ //表单验证
  nickname: [{ required: true, trigger: 'blur', message: '请输入昵称' }, { min: 2, max: 6, message: '昵称在2~6个' }],
  phone: [{ required: true, trigger: 'blur', message: '请输入手机号' }, { validator: validatePhone, trigger: 'blur' }],
  gender: [{ required: true, trigger: 'change', message: '请选择性别' }],
  status: [{ required: true, trigger: 'change', message: '请选择用户等级' }],
  level: [{ required: true, trigger: 'change', message: '请选择用户状态' }]
})

/**
 * 用户编辑
 */
function Useredit(params: string) {
  centerDialogVisible.value = true
  Object.assign(ruleForm, params)
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let data = {
        _gp: 'admin.user',
        _mt: 'edit',
        user: JSON.stringify(ruleForm)
      }
      post(data).then(res => {
        console.log(res);
        let { errno, errmsg } = res
        if (200 == errno) {
          getdata()
          centerDialogVisible.value = false
          ElMessage.success("修改成功")
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}


// 初始化数据
function getdata() {
  let data = {
    _gp: 'admin.user',
    _mt: 'list',
    id: Userbinding.id,
    nickname: Userbinding.nickname,
    level: Userbinding.level,
    gender: Userbinding.gender,
    status: Userbinding.status,
    pageNo: listdata.page,
    limit: listdata.limit
  }
  post(data).then(res => {
    console.log(res);
    let { data } = res
    tableData.list.length = 0
    tableData.list.push(...data.items)
    listdata.total = data.total
  })
}
getdata()

/**
 * 激活用户状态
 */
function ActivateUser(params: { id: string, status: string }) {
  let data = {
    _gp: 'admin.user',
    _mt: 'editStatus',
    userId: params.id,
    status: params.status ? '0' : '1'
  }
  post(data).then(res => {
    console.log(res);
    let { errno, errmsg } = res
    if (200 == errno) {
      getdata()
      ElMessage.success(params.status ? '激活成功' : '冻结成功')
    } else {
      ElMessage.warning(errmsg)
    }
  })
}

/**
 * 用户查找
 */
function userlookup() {
  getdata()
}

</script>

<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
